import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';

class HttpClient {
  static final HttpClient _instance = HttpClient._internal();
  factory HttpClient() => _instance;

  late Dio dio;

  HttpClient._internal() {
    BaseOptions options = BaseOptions(
      baseUrl: 'https://toys.mtoys.cc/api/', // 你的 API 基础 URL
      headers: {"content-type": "application/json", "app-type": "user"},
      connectTimeout: const Duration(seconds: 5), // 增加超时时间
      receiveTimeout: const Duration(seconds: 5), // 增加超时时间
    );
    dio = Dio(options);

    // 添加拦截器以便调试和处理 Token
    dio.interceptors.add(InterceptorsWrapper(
      onRequest: (options, handler) async {
        // 从缓存中获取 Token
        SharedPreferences prefs = await SharedPreferences.getInstance();
        String? token = prefs.getString('token');
        options.headers['token'] = token;
        // print('Request: ${options.method} ${options.path}');
        // print('Request headers: ${options.headers}');
        return handler.next(options);
      },
      onResponse: (response, handler) {
        print('-----Response: ${response.statusCode} ${response.data}');
        return handler.next(response);
      },
      onError: (DioException e, handler) {
        print('Error: ${e.response?.statusCode} ${e.message}');
        return handler.next(e);
      },
    ));
  }

  // GET 请求
  Future<Response> get(String path,
      {Map<String, dynamic>? queryParameters}) async {
    print('-----GET: $queryParameters');
    return await dio.get(path, queryParameters: queryParameters);
  }

  // POST 请求
  Future<Response> post(String path, {Map<String, dynamic>? data}) async {
    print('-----post: $data');
    return await dio.post(path, data: data);
  }

  // 保存 Token 到缓存
  Future<void> saveToken(String token) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString('token', token);
  }

  // 获取 Token 从缓存
  Future<String?> getToken() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getString('token');
  }

  // 删除 Token 从缓存
  Future<void> deleteToken() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.remove('token');
  }

// 其他请求方法...
}
